<!--
 * @Author: your name
 * @Date: 2022-03-04 23:05:49
 * @LastEditTime: 2022-03-04 23:24:38
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \算法测试\day0906\懒加载.html
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图片懒加载</title>
    <style>
      img {
        width: 100%;
        height: 600px;
      }
    </style>
  </head>
  <body>
    <div style="height: 2000px;"></div>
    <img
    data-src="https://cdn.pixabay.com/photo/2021/08/24/15/38/sand-6570980_960_720.jpg"
      alt="1"
      style="height: 2000px;"
    />
    <img
    src=""
    data-src="https://cdn.pixabay.com/photo/2013/02/21/19/06/drink-84533_960_720.jpg"
      alt="2"
    />
    <script>
      const images = document.querySelectorAll("img");
      const lazyLoad = () => {
          console.log(1);
        images.forEach((item) => {
          // 触发条件为img元素的CSSOM对象到视口顶部的距离 < 100px + 视口高度，+100px为了提前触发图片加载
          if (
            item.getBoundingClientRect().top <
            document.documentElement.clientHeight + 100
          ) {
            if ("src" in item.dataset) {
              item.src = item.dataset.src;
            }
          }
        });
      };
      document.addEventListener("scroll",lazyLoad);//滚动条滚动
    </script>
    <!-- 方法二 loading="lazy" -->
     <!-- <div style="height: 2000px;"></div>
     <img src="https://fanyi-cdn.cdn.bcebos.com/static/translation/img/header/logo_e835568.png" alt="" loading="lazy" style="width: 100px;height: 100px;"> -->
  </body>
</html>